<template>
	<NavBar :obj="{ title: '新增收货地址', color: '#000', backgroundColor: '#fff' }" />

	<view class="layout-box">
		<view class="layout">
			<view class="label">收货人</view>
			<input class="inp" placeholder-class="place-inp" placeholder="请填写收货人姓名" v-model="formRef.nickname" />
		</view>
		<view class="layout">
			<view class="label">手机号码</view>
			<input class="inp" placeholder-class="place-inp" placeholder="请填写收货人手机号码" v-model="formRef.tel" />
		</view>
		<view class="layout">
			<view class="label">所在省市</view>
			<view class="tips" :class="{ inp: formRef.address, 'place-inp': !formRef.address }" @click="pickArea">{{ formRef.address ? formRef.address : '点击选择所在省市区' }}</view>
			<up-icon name="arrow-down" size="15" class="icon" color="#bdbdbd"></up-icon>
		</view>
		<view class="layout">
			<view class="label">详细地址</view>
			<textarea class="inp textarea" placeholder-class="place-inp" placeholder="请填写详细地址" v-model="formRef.details"></textarea>
		</view>
	</view>

	<view class="default flex items-center justify-between">
		<view class="left">
			<view class="title">设为默认地址</view>
			<view class="desc">下单时会优先使用该地址</view>
		</view>
		<view class="right">
			<up-switch v-model="formRef.default" activeColor="#FB3204" :activeValue="1" :inactiveValue="0"></up-switch>
		</view>
	</view>

	<view class="fixed-bottom">
		<view class="btn" @click="saveAddressInfo">
			<text>保存</text>
		</view>
	</view>

	<up-picker
		confirmColor="#F81A2E"
		:show="areaShow"
		ref="uPickerRef"
		:defaultIndex="defaultIndex"
		keyName="title"
		:loading="pickerLoading"
		:columns="columns"
		:closeOnClickOverlay="true"
		@close="areaShow = false"
		@confirm="confirm"
		@cancel="areaShow = false"
		@change="changeHandler"
	></up-picker>
</template>

<script setup>
	import { ref, nextTick, reactive } from 'vue';
	import { port, goUrl, hint, loading, closeLoading, goBack, goIndex } from '../../service/port';
	import { onLoad, onShow, onReachBottom } from '@dcloudio/uni-app';

	const areaRef = ref({
		level: 0,
		pid: 0
	});
	const choose = ref('');
	const defaultIndex = ref([0, 0, 0]);
	const formRef = ref({
		id: '',
		nickname: '',
		tel: '',
		province: '',
		city: '',
		district: '',
		details: '',
		default: 0,
		address: ''
	});

	const areaShow = ref(false);
	const uPickerRef = ref(null);
	const pickerLoading = ref(false);

	const columns = ref([['请选择省'], ['请选择市'], ['请选择区/县']]);
	const init = ref(false);
	const changeHandler = async (e) => {
		pickerLoading.value = true;
		const { columnIndex, value, values, index, indexs } = e;

		if (columnIndex < 2) {
			await getArea(columnIndex + 1, columns.value[columnIndex][index].id);
			if (!columnIndex) {
				await nextTick();
				await getArea(columnIndex + 2, columns.value[columnIndex + 1][0].id);
				pickerLoading.value = false;
			}

			if (!columnIndex) {
				defaultIndex.value = [index, 0, 0];
			} else {
				indexs[2] = 0;
				defaultIndex.value = indexs;
			}
			nextTick(() => {
				uPickerRef.value?.setIndexs(defaultIndex.value);
			});
			pickerLoading.value = false;
		} else {
			defaultIndex.value[2] = index;
			pickerLoading.value = false;
		}
	};

	const confirm = (e) => {
		let a = '',
			k = ['province', 'city', 'district'];
		defaultIndex.value.map((v, i) => {
			a += columns.value[i][v].title;
			formRef.value[k[i]] = columns.value[i][v].id;
		});
		formRef.value.address = a;
		areaShow.value = false;
	};

	onLoad((e) => {
		if (e.id) {
			formRef.value.id = e.id;
		}
		choose.value = e.choose;
	});

	onShow(() => {
		if (formRef.value.id) {
			getAddressInfo();
		}
	});

	async function getAddressInfo() {
		let res = await port('getAddressInfo', { id: formRef.value.id });
		formRef.value = {
			...res.data
		};
		await getNextArea();
	}

	async function saveAddressInfo() {
		if (!formRef.value.nickname) {
			hint('请填写收货人');
			return false;
		}
		if (!formRef.value.tel) {
			hint('请填写手机号号码');
			return false;
		}
		if (!formRef.value.province || !formRef.value.city || !formRef.value.district) {
			hint('请选择所在省市区');
			return false;
		}

		if (!formRef.value.details) {
			hint('请填写详细地址');
			return false;
		}
		loading();
		let res = await port('saveAddressInfo', formRef.value);

		setTimeout(() => {
			closeLoading();
			hint(res.msg);
			if (choose.value) {
				formRef.value.id = res.data;
				uni.setStorageSync('chooseAddress', formRef.value);
				goIndex('/pages/order/index');
			} else {
				goBack();
			}
		}, 200);
	}

	async function pickArea() {
		if (!init.value) {
			loading();
			await getNextArea();
		}
		areaShow.value = true;
	}

	async function getNextArea() {
		loading();
		await getArea();
		await nextTick();
		if (formRef.value.id) {
			await getArea(1, formRef.value.province);
			await nextTick();
			await getArea(2, formRef.value.city);

			let k = ['province', 'city', 'district'];
			defaultIndex.value.forEach((v, i) => {
				columns.value[i].forEach((vv, ii) => {
					if (vv.id == parseInt(formRef.value[k[i]])) {
						defaultIndex.value[i] = ii;
					}
				});
			});

			nextTick(() => {
				uPickerRef.value?.setIndexs(defaultIndex.value);
			});
		} else {
			await getArea(1, columns.value[0][defaultIndex.value[0]].id);
			await nextTick();
			await getArea(2, columns.value[1][defaultIndex.value[1]].id);
		}

		closeLoading();
		init.value = true;
	}

	async function getArea(level = 0, pid = 0) {
		let res = await port('getArea', { level: level, pid: pid });
		columns.value[level] = res.data;
	}
</script>

<style scoped lang="scss">
	:global(page) {
		background-color: #f4f5f8;
	}
	.tips {
		font-size: 28rpx;
		color: #bdbdbd;
	}
	.default {
		background: #ffffff;
		border-radius: 20rpx;
		margin: 26rpx 30rpx;
		padding: 40rpx 23rpx;
		.left {
			.title {
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
			}
			.desc {
				font-weight: 400;
				font-size: 24rpx;
				color: #bdbdbd;
				margin-top: 15rpx;
			}
		}
	}

	.layout-box {
		background: #ffffff;
		border-radius: 20rpx;
		margin: 26rpx 30rpx;
		padding: 0 23rpx;
		.layout {
			padding: 30rpx 0;
			border-bottom: 1rpx solid #eeeeee;
			display: flex;

			justify-content: space-between;
			&:last-child {
				border-bottom: none;
			}
			.label {
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
				width: 27%;
			}
			.inp {
				font-size: 28rpx;
				color: #333333;
				flex: 1 1 0%;
			}
			.place-inp {
				color: #bdbdbd;
				flex: 1 1 0%;
			}
			.textarea {
				height: 120rpx;
			}
			.icon {
				margin-right: 30rpx;
			}
		}
	}
</style>
